<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--视频源数据-->
            <el-col :span="24" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                    label-width="88px">
                    <el-form-item label="视频源名称" prop="cameraName">
                        <el-input v-model="queryParams.cameraName" placeholder="请输入视频源名称" clearable style="width: 240px"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                            v-hasPermi="['mes:dv:machinery:add']">新增</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="machineryList" border >
                    <el-table-column label="序列号"  align="center" key="deviceSerial" prop="deviceSerial"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="视频源编码" align="center" key="cameraNo" prop="cameraNo">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="handleView(scope.row)"
                                v-hasPermi="['mes:dv:machinery:query']">{{ scope.row.cameraNo }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="视频源名称"  align="center" key="cameraName" prop="cameraName"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="备注"  align="center" key="remark" prop="remark" />
                    <el-table-column label="创建时间" align="center" prop="createTime">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-hasPermi="['mes:dv:machinery:edit']">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-video-play" @click="lookView(scope.row)"
                                v-hasPermi="['sale:purchase:edit']">播放</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['mes:dv:machinery:remove']">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageSize"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 添加或修改视频源对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="视频源编码" prop="itemCode">
                            <el-input v-model="form.cameraNo" readonly="readonly" maxlength="64"
                                v-if="optType == 'view'" />
                            <el-input v-model="form.cameraNo" placeholder="请输入视频源编码" maxlength="64" v-else />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="视频源名称" prop="itemName">
                            <el-input v-model="form.cameraName" maxlength="255" readonly="readonly"
                                v-if="optType == 'view'" />
                            <el-input v-model="form.cameraName" placeholder="请输入视频源名称" maxlength="255" v-else />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" readonly
                                v-if="optType == 'view'"></el-input>
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" v-else></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
                <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 视频弹窗 -->
        <el-dialog :title="'视频源播放'" :visible.sync="openView" width="960px" append-to-body>
            <div id="video-container"></div>
        </el-dialog>
    </div>
</template>

<script>
var player = null;
import { getMonitorToken, listThorough, getThorough, delThorough, addThorough, updateThorough } from "@/api/monitor/workShop";
var themeData = {
    "header": {
        "color": "#1890ff",
        "activeColor": "#FFFFFF",
        "backgroundColor": "#000000",
        "btnList": [
            {
                "iconId": "deviceID",
                "part": "left",
                "defaultActive": 0,
                "memo": "顶部设备序列号",
                "isrender": 1
            },
            {
                "iconId": "deviceName",
                "part": "left",
                "defaultActive": 0,
                "memo": "顶部设备名称",
                "isrender": 1
            },
            {
                "iconId": "cloudRec",
                "part": "right",
                "defaultActive": 0,
                "memo": "云存储",
                "isrender": 0
            },
            {
                "iconId": "rec",
                "part": "right",
                "defaultActive": 0,
                "memo": "SD卡回放",
                "isrender": 0
            }
        ]
    },
    "footer": {
        "color": "#FFFFFF",
        "activeColor": "#1890FF",
        "backgroundColor": "#00000021",
        "btnList": [
            {
                "iconId": "play",
                "part": "left",
                "defaultActive": 1,
                "memo": "播放",
                "isrender": 1
            },
            {
                "iconId": "capturePicture",
                "part": "left",
                "defaultActive": 0,
                "memo": "截屏按钮",
                "isrender": 1
            },
            {
                "iconId": "sound",
                "part": "left",
                "defaultActive": 0,
                "memo": "声音按钮",
                "isrender": 1
            },
            {
                "iconId": "pantile",
                "part": "left",
                "defaultActive": 0,
                "memo": "云台控制按钮",
                "isrender": 1
            },
            {
                "iconId": "recordvideo",
                "part": "left",
                "defaultActive": 0,
                "memo": "录制按钮",
                "isrender": 1
            },
            {
                "iconId": "talk",
                "part": "left",
                "defaultActive": 0,
                "memo": "对讲按钮",
                "isrender": 1
            },
            {
                "iconId": "zoom",
                "part": "left",
                "defaultActive": 0,
                "memo": "电子放大",
                "isrender": 1
            },
            {
                "iconId": "hd",
                "part": "right",
                "defaultActive": 0,
                "memo": "清晰度切换按钮",
                "isrender": 1
            },
            {
                "iconId": "webExpend",
                "part": "right",
                "defaultActive": 0,
                "memo": "网页全屏按钮",
                "isrender": 1
            },
            {
                "iconId": "expend",
                "part": "right",
                "defaultActive": 0,
                "memo": "全局全屏按钮",
                "isrender": 1
            }
        ]
    }
};
export default {
    name: "workshopMonitor",
    data() {
        return {
            optType: undefined,
            // 遮罩层
            loading: true,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 物料产品表格数据
            machineryList: [],
            // 弹出层标题
            title: "",
            // 视频源类型树选项
            machineryTypeOptions: [],
            //车间选项
            workshopOptions: [],
            // 是否显示弹出层
            open: false,
            // 是否显示视频播放弹出层
            openView: false,
            // 视频源类型名称
            machineryTypeName: undefined,
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "machineryTypeName"
            },
            // 序列号
            deviceSerial: '',
            // 查询参数
            queryParams: {
                page: 0,
                pageSize: 10,
                cameraNo: null,
                cameraName: null,
            },

            // 表单校验
            rules: {
                cameraNo: [
                    { required: true, message: "视频源编码不能为空", trigger: "blur" },
                    { max: 64, message: '视频源编码长度必须小于64个字符', trigger: 'blur' }
                ],
                cameraName: [
                    { required: true, message: "视频源名称不能为空", trigger: "blur" }
                ],
            }
        };
    },
    watch: {
        // 根据视频源分类名称筛选分类树
        machineryTypeName(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        const { deviceSerial } = this.$route.query
        this.deviceSerial = deviceSerial
        this.getList();
    },
    methods: {

        /** 查询列表 */
        async getList() {
            // 使用axios发送get请求
            this.loading = true;
            listThorough({ ...this.queryParams, deviceSerial: this.deviceSerial }).then(response => {
                let data = response.data
                this.machineryList = data.content;
                this.total = data.totalElements;
                this.loading = false;
            }
            );
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                cameraNo: null,
                cameraName: null,
                remark: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageSize = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 查询明细按钮操作
        handleView(row) {
            this.reset();
            const id = row.id
            getThorough(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "查看视频源信息";
                this.optType = "view";
            });
        },
        /** 新增按钮操作 */
        handleAdd() {
            debugger;
            this.reset();
            this.optType = "add";
            this.open = true;
            this.title = "新增视频源";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id
            getThorough(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改视频源";
                this.optType = "edit";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.deviceSerial = this.deviceSerial
                    if (this.form.id != undefined) {
                        updateThorough(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        debugger;
                        addThorough(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const id = row.id;
            this.$modal.confirm('确认删除数据项？').then(function () {
                return delThorough(id);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch((err) => {
                console.log(err);
            });
        },
        /** 播放视频源操作 */
        async lookView(row) {
            this.openView = true
            let accessToken = await this.getToken()
            if(window.player){
                this.destroy();
            }
            player = new EZUIKit.EZUIKitPlayer({
                id: 'video-container', // 视频容器ID
                accessToken: accessToken,
                url: `ezopen://open.ys7.com/${row.deviceSerial}/${row.cameraNo}.live`,
                themeData: themeData,
                height: 660
            });
            window.player = player;
        },
        destroy() {
            var destroyPromise = window.player.destroy();
            destroyPromise.then((data) => {
                console.log("promise 获取 数据", data);
            });
            player = null;
        },
        checkToken() {
            const tokenInfo = localStorage.getItem('monitorToken');
            if (!tokenInfo) {
                // 如果没有token信息，直接返回false
                return false;
            }

            const { token, expiresAt } = JSON.parse(tokenInfo);
            const now = new Date().getTime();
            // 检查token是否过期
            if (now > expiresAt) {
                // 清除过期token
                localStorage.removeItem('monitorToken');
                return false;
            }

            // 如果token有效，则返回token
            return token;
        },

        // 获取token，如果本地没有或已过期，则通过AJAX请求获取
        async getToken() {
            let token = this.checkToken();
            if (token) {
                // 如果token有效，直接使用
                console.log('使用本地token:', token);
                return token;
            }
            // 如果token无效或不存在，则通过AJAX请求新的token
            let res = await getMonitorToken()
            token = res.data
            // 假设data.token是获取的token，data.expires_in是token的过期时间（秒）
            const expiresIn = 5 * 24 * 60 * 60 * 1000; // 转换为毫秒
            const expiresAt = new Date().getTime() + expiresIn;
            const tokenInfo = JSON.stringify({ token: token, expiresAt: expiresAt });
            // 存储token信息到localStorage
            localStorage.setItem('monitorToken', tokenInfo);
            console.log('新token已存入localStorage:');
            return token
        }
    }
};
</script>